<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Callout;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\DB;
use Dcat\Admin\Form;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Tab;
use App\Models\Project;
use App\Models\ProjectPlan;
use App\Models\ProjectUser;
use App\Models\Device;
use App\Models\DeviceLog;
use App\Models\Company;
use App\Models\Cabinet;
use App\Models\CabinetPoint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
use Encore\Admin\Controllers\HasResourceActions;
use Faker\Factory;
use Dcat\Admin\Widgets\Dropdown;
use Dcat\Admin\Widgets\Card;
use App\Admin\Renderable\DeviceTable;
use Illuminate\Support\Facades\Route;
use App\Handlers\WeconHandler;
use App\Models\AdminUser;
use Hamcrest\Arrays\IsArray;
use Symfony\Component\VarDumper\VarDumper;

class ProjectController extends Controller
{

    public function index(Content $content)
    {
        return $content
            ->header('项目列表')
            ->description()
//            ->body(Callout::make('即将在下个版本发布，敬请期待~'))
           // ->body($this->build())
            ->body($this->grid());
    }
    public function Pproject($id,Content $content){
        return $content
            ->header('项目列表')
            ->description()
            ->body($this->grid($id));
    }
    protected function grid($id = 0)
    {
        if(Admin::user()->id==1){
            $list = Project::pluck('projectId');
        }else{
            // 所有授权项目
            $list = ProjectUser::where(['user_id'=>Admin::user()->id])->pluck('projectId');
        }
        if($id == 0){
            $where = array();
        }else{
            $list = ProjectUser::where(['user_id'=>Admin::user()->id])->pluck('projectId');
            $where['companyId'] = $id;
        }
        
        return new Grid(Project::whereIn('projectId',$list)->where($where), function (Grid $grid) {
            $grid->disableColumnSelector();
            // $grid->content->expand(function (Grid\Displayers\Expand $expand) {
            //     // 设置按钮名称
            //     $expand->button($this->projectname);
            //     return DeviceTable::make();
            // });
            $grid->column('projectId','ID');
            // $grid->column('projectname','项目名称');
            $grid->column('projectname','项目名称')->limit(50)->link(function () {
                $cabinet = Cabinet::where(['project_id'=>$this->getKey(),'pid'=>0])->first();
                if(isset($cabinet)){
                    return admin_url('cabinet-children/'.$cabinet->id);
                }else{
                    return admin_url('Project');
                }
            });
            $grid->column('remark','项目说明');
            $grid->column('created_at','创建时间');
            $grid->column('user_id','创建人')->display(function($userId) {
                return Db::table('admin_users')->where(['id'=>$userId])->value('name');;
            });
            $grid->column('companyId','公司')->display(function($companyId) {
                return Db::table('xfy_company')->where(['companyId'=>$companyId])->value('name');;
            });
            $grid->column('lat','纬度');
            $grid->column('lng','经度');
            // 启用边框模式
            $grid->withBorder();
            $grid->fixColumns(2);
            //显示详情按钮
            // $grid->showViewButton();
            $grid->disableViewButton();
            //操作按钮
            $grid->showActions();
            // $grid->disableActions();
            // $grid->disableBatchDelete();
            // 禁用创建按钮
            $grid->disableCreateButton();
            $url = admin_base_path('Project/create');
            $a = Admin::user()->roles->toArray();
            if($a[0]['id']!=9){ //超级管理员可以删除
                $grid->tools("<a href='$url' class='btn btn-primary btn-outline'><i class='feather'>新增</a>");
            }
            
            // 创建按钮
            // $grid->showCreateButton();
            // 禁用详情按钮
            // $grid->disableViewButton();
            // 禁用编辑按钮
            $grid->disableEditButton();
            // 显示编辑按钮
            // $grid->showEditButton();
            // 禁用快捷编辑按钮
            $grid->disableQuickEditButton();
            // 显示快捷编辑按钮
            // $grid->showQuickEditButton();
            // 设置弹窗宽高，默认值为 '700px', '670px'
            // $grid->setDialogFormDimensions('50%', '60%');
            // $grid->enableDialogCreate();
            // 禁用删除按钮
            $grid->disableDeleteButton();
            // $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
            //     $create->text('projectname', '项目名称');
            //     $create->text('remark', '项目说明');
            //     $create->select('projectId', '所属公司')->options([
            //         1 => 'foo',
            //         2 => 'bar',
            //     ]);
            //     $create->decimal('lat', '纬度');
            //     $create->decimal('lng', '经度');
            // });
            // 显示删除按钮
            $a = Admin::user()->roles->toArray();
            if($a[0]['id']==5){ //超级管理员可以删除
                $grid->showDeleteButton();
            }
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $id = $actions->getKey();
                $edit_url = admin_base_path('Project/'.$id.'/edit');
                $actions->append("<a href='$edit_url'><i class='feather icon-edit-1 grid-action-icon'></i></a>");
                // $actions->append('<a href="/admin/project/ProjectLocation/'.$id.'"><i class="fa fa-location-arrow"></i></a>');
                $plan = ProjectPlan::where('project_id', $id)->first();
                $actions->append('&nbsp;<a href="/admin/report/'.$id.'"><i class=" fa fa-sticky-note-o"></i></a>');
                // print_r($plan->id);die;
                if(isset($plan)){
                    $actions->append('&nbsp;<a href="/admin/project/ProjectLocationView/'.$plan->id.'"><i class="fa fa-puzzle-piece"></i></a>');
                    //$actions->append('&nbsp;<a href="/admin/project/ProjectLocation/'.$plan->id.'"><i class="fa fa-magic"></i></a>');
                    
                }
                $actions->append('&nbsp;<a title="项目管理" href="/admin/project-layer/'.$id.'"><i class="fa fa-image"></i></a>');
            });
        });
    }
    public function ProjectLocationView($id,Content $content){
        $sessionKey = 'location_refresh';
        $autoRefresh = session($sessionKey) ? session($sessionKey) : 60;
        
        $plane = ProjectPlan::where(['id'=>$id])->first();
        $project = Project::where(['projectId'=>$plane['project_id']])->first()->toArray();
        if(isset($project)&&$project['project_type']==1){
            $point = Device::where(['projectId'=>$plane['project_id']])->select('devicename as name','deviceId as id','width','height','heartbeat')->get()->toArray();
        }else{
            $Cabinet = Cabinet::where(['planeJPG'=>$id])->get()->toArray();
            $Cabinet_ids = array_column($Cabinet,'id');
            $box = Cabinet::whereIn('pid',$Cabinet_ids)->get()->toArray();
            $ids = array_column($box,'id');
            $point = CabinetPoint::whereIn('cabinet_id',$ids)->get()->toArray();
        }
        // print_r($point);die;
        if(isset($plane['jsonurl'])&&$plane['jsonurl']!=''){ //存在文件
            $json = file(public_path($plane['jsonurl']));
            $point = json_decode($json[0]);
        }
        // print_r($point);die;
        $res = ProjectPlan::where('project_id',$plane['project_id'])->get(['name','id'])->toArray();
        // foreach($box as $value){
        //     foreach($point as &$pval){
        //         if($value['id']==$pval['cabinet_id']){
        //             $pval['color'] = $value['color'];
        //         }
        //     }
        // }
        foreach($res as &$val){
            if($id==$val['id']){
                $val['checked'] = 'true';
            }else{
                $val['checked'] = 'false';
            }
        }
        // print_r($res);die;
        return $content
            ->header($plane['name'].'')
            ->body(view('admin.ProjectLocation.LocationView',['planeJPG'=>'/uploads/'.$plane['image'],'data'=>json_encode($point),'pid'=>$plane['project_id'],'list'=>$res,'id'=>$id,'autoRefresh'=>$autoRefresh]));
    }
    public function setLocationsAutoRefresh(Request $request){
        $param = $request->all();
        $key = 'location_refresh';
        $r = session()->put($key, $param['value']);
        return response()->json(['code'=>1, 'data' => [], 'msg' => 'success']);
    }
    public function ProjectLocation($id,Content $content){
        
        // $Cabinet = Cabinet::where(['planeJPG'=>$id])->get()->toArray();
        // if(!isset($Cabinet['jsonurl'])){
        // $Cabinet_ids = array_column($Cabinet,'id');
        // $box = Cabinet::whereIn('pid',$Cabinet_ids)->get()->toArray();
        // $ids = array_column($box,'id');
        // $point = CabinetPoint::whereIn('cabinet_id',$ids)->get()->toArray();
        // print_r($point);die;
        // }else{
        //     // Storage::disk('orange')->get();
        //     $json_string = file_get_contents($Cabinet['jsonurl']);
        //     var_dump($json_string);die;
        // }
        // $Cabinet_ids = array_column($Cabinet,'id');
        // $box = Cabinet::whereIn('pid',$Cabinet_ids)->get()->toArray();
        // $ids = array_column($box,'id');
        // $point = CabinetPoint::whereIn('cabinet_id',$ids)->get()->toArray();
        // $result = array_merge($box,$point);
        $plane = ProjectPlan::where(['id'=>$id])->first()->toArray();
        
        $project = Project::where(['projectId'=>$plane['project_id']])->first()->toArray();
        // print_r($project);die;
        if(isset($project)&&$project['project_type']==1){
            $point = Device::where(['projectId'=>$plane['project_id']])->select('devicename as name','deviceId as id','width','height','heartbeat','cid')->get()->toArray();
        }
        if(isset($plane['jsonurl'])&&$plane['jsonurl']!=''){ //存在文件
            $json = file(public_path($plane['jsonurl']));
            $point = json_decode($json[0]);
        }
        $res = ProjectPlan::where('project_id',$plane['project_id'])->get(['name','id'])->toArray();
        // foreach($box as $value){
        //     foreach($point as &$pval){
        //         if($value['id']==$pval['cabinet_id']){
        //             $pval['color'] = $value['color'];
        //         }
        //     }
        // }
        
        foreach($res as &$val){ //楼层
            if($id==$val['id']){
                $val['checked'] = 'true';
            }else{
                $val['checked'] = 'false';
            }
        }
        $url='';
        // print_r($point);die;
        if($point=''){
            $data='';
        }else{
            $data = json_encode($point);
        }
        return $content
            ->header($plane['name'].'设备位置')
            ->body(view('admin.ProjectLocation.Location',['planeJPG'=>'/uploads/'.$plane['image'],'data'=>$data,'list'=>$res,'url'=>$url,'id'=>$id]));
    }
    public function getLocationsData(Request $request){
        $info = $request->all();
        $id = $info['id'];
        $plane = ProjectPlan::where(['id'=>$id])->first()->toArray();
        $project = Project::where(['projectId'=>$plane['project_id']])->first()->toArray();
        $alarm = [];
        
        if(Redis::exists($plane['project_id'])){
            $alarm = Redis::get($plane['project_id']);
        }
        // if(isset($project)&&$project['project_type']==1){
            // $point = Device::where(['projectId'=>$plane['project_id']])->select('devicename as name','deviceId as id','width','height')->get()->toArray();
        // }else{
        //     $Cabinet = Cabinet::where(['planeJPG'=>$id])->get()->toArray();
        //     $Cabinet_ids = array_column($Cabinet,'id');
        //     $box = Cabinet::whereIn('pid',$Cabinet_ids)->get()->toArray();
        //     $ids = array_column($box,'id');
        //     $point = CabinetPoint::whereIn('cabinet_id',$ids)->get()->toArray();
        //     // foreach($box as $value){
        //     //     foreach($point as &$pval){
        //     //         if(!is_array($pval)){
        //     //             $pval = json_decode($pval,1);
        //     //         }
        //     //         // print_r($pval);die;
        //     //         if($value['id']==$pval['cabinet_id']){
        //     //             $pval['color'] = $value['color'];
        //     //         }
        //     //     }
        //     // }
        //     $arr = [];
        //     foreach($box as $val){
        //         $list = WeconHandler::getRealtimeData($val['box_id'], $val['group_id']);
        //         if(empty($arr)){
        //             $arr = $list;
        //         }else{
        //             if(!empty($list)){
        //                 $arr = array_merge($arr,$list);
        //             }
                    
        //         }
        //     }
        //     if($arr){
        //         $latestData = [];
        //         foreach($point as &$pval){
        //             if(!is_array($pval)){
        //                 $pval = json_decode($pval,1);
        //             }
        //             // print_r($pval);die;
        //             foreach ($arr as $onePoint) {
        //                 if($pval['alias']=='a_'.$onePoint['monitorId']){
        //                     $pval['name'] = $pval['name'].'：'.$onePoint['value'];
        //                 }
        //                 // $latestData['a_'.$onePoint['monitorId']] = $onePoint['value'];
        //             }
        //         }
        //     };
        // }
        if(isset($plane['jsonurl'])&&$plane['jsonurl']!=''){ //存在文件
            $json = file(public_path($plane['jsonurl']));
            $point = json_decode($json[0],1);
        }
        // print_r($point);die;
        if($id==8){ //安舍
            if(Redis::exists('192.168.2.102')){
                $redisarr = json_decode(Redis::get('192.168.2.102'),1);
                
                $alarm = [];
                foreach($point as $key => &$val){
                    $value = json_decode($val,1);
                    if(isset($redisarr['04'][$value['cid']])&&($redisarr['04'][$value['cid']]['status']==1)){//是否存在故障
                        $alarm[$value['cid']] = '192.168.2.102|'.$value['cid'].'|存在故障';
                    }
                    if(isset($redisarr['28'][$value['cid']])&&($redisarr['28'][$value['cid']]['status']==1)){//是否存在故障
                        $alarm[$value['cid']] = '192.168.2.102|'.$value['cid'].'|发生火警';
                    }
                }
                if($redisarr['0c']['status']==1){
                    $alarm['0c'] = '192.168.2.102电源故障';
                }
                if($redisarr['44']['status']==1){
                    $alarm['44'] = '192.168.2.102开锁';
                }
                if($redisarr['c8']['status']==1){
                    $alarm['c8'] = '192.168.2.102回路故障';
                }
                if($redisarr['38']['status']==1){
                    $alarm['38'] = '192.168.2.102技术报警';
                }
                if(!empty($alarm)){
                    $alarm = json_encode($alarm);
                }
            }
            
            // if(Redis::exists('192.168.2.102')){
            //     $redisarr = json_decode(Redis::get('192.168.2.102'),1);
            //     print_r($redisarr);die;
            // }
        }
        // foreach($res as &$val){
        //     if($id==$val['id']){
        //         $val['checked'] = 'true';
        //     }else{
        //         $val['checked'] = 'false';
        //     }
        // }
        // print_r($point);die;
        return response()->json(['code'=>1, 'data' => $point,'alarm'=>$alarm, 'msg' => 'success']);
    }
    public function ReleaseAlarm(Request $request){
        
        $info = $request->all();
        print_r($info);die;
        if($info['pid']==46){
            $msg = explode('|',$info['msg']);
            if(isset($msg[2])){
                if($msg[2] == '存在故障'){
                    $errorcode = '04';
                }else{
                    $errorcode = '28';
                }
            }else{
                switch($msg[1]){
                    case '电源故障' :  $errorcode = '0c';
                    case '开锁' :  $errorcode = '44';
                    case '回路故障' :  $errorcode = 'c8';
                    case '技术报警' :  $errorcode = '38';
                }
            }
            $device = Device::where(['cid'=>$info['id']])->first()->toArray();
            $param['deviceId'] = $device['deviceId'];
            $param['user_id'] = Admin::user()->id;
            $param['msg'] = $info['msg'];
            $param['created_at'] = date('Y-m-d H:i:s');
            DeviceLog::insert($param);
        }else{
            $device = Device::where(['cid'=>$info['id']])->first()->toArray();
            $param['deviceId'] = $device['deviceId'];
            $param['user_id'] = Admin::user()->id;
            $param['msg'] = $info['msg'];
            $param['created_at'] = date('Y-m-d H:i:s');
            DeviceLog::insert($param);
            $url = '/json/'.$device['planeJPG'].'.json';
            $json = file(public_path($url));
            $point = json_decode($json[0],1);
            foreach($point as $key => &$value){
                if($value['name']==$info['id']){
                    $value['type'] = 1;
                }
                $value = json_encode($value);
            }
            $file = public_path('/json/' . $device['planeJPG'].'.json');
            file_put_contents($file, json_encode($point));
            if(Redis::exists($device['projectId'])){
                $alarm = Redis::get($device['projectId']);
                $a = json_decode($alarm,1);
                $key = array_search($info['msg'],$a[$device['cid']]);
                // unset($a[])
                unset($a[$device['cid']][$key]);
                if(empty($a[$device['cid']])){
                    unset($a[$device['cid']]);
                }
                Redis::set($device['projectId'],json_encode($a));
            }
        }
        
        return response()->json(['code'=>1, 'msg' => '操作成功']);
    }
    public function ProjectLocationSave(Request $request){
        $info = $request->all();
        // $Cabinet = Cabinet::where(['planeJPG'=>$info['id']])->get()->toArray();
        $file = public_path('/json/' . $info['id'].'.json');
        file_put_contents($file, json_encode($info['data']));
        ProjectPlan::where(['id'=>$info['id']])->update(['jsonurl'=>'/json/' . $info['id'].'.json']);
        // foreach($info['data'] as $val){
        //     $arr = json_decode($val,1);
        //     if($arr['isbox']==1){
        //         Cabinet::where(['id'=>$arr['id'],'name'=>$arr['text']])->update(['pageX'=>$arr['pageX'],'pageY'=>$arr['pageY']]);
        //     }else{
        //         CabinetPoint::where(['id'=>$arr['id'],'name'=>$arr['text']])->update(['pageX'=>$arr['pageX'],'pageY'=>$arr['pageY']]);
        //     }
        // }
        return array('resultCode'=>1,'resulMsg'=>'保存成功!');
    }

    public function update($id){
        return $this->form()->update($id);
    }
    public function store(){
        return $this->form()->store();
    }

    public function create(Content $content){
        return $content
            ->title('新增项目')
            ->description('创建')
            // ->body($this->buildPreviewButton())
            // ->body($this->newline())
            ->body($this->form());
    }
    public function form(){
        return Form::make(Project::with('plans'), function (Form $form) {
            $form->block(8, function (Form\BlockForm $form) {
                // 设置标题
                $form->title('基本设置');
                // 显示底部提交按钮
                $form->showFooter();
                // 设置字段宽度
                $form->width(9, 3);
                // $form->display('user_id', 'ID');
                $form->column(6, function (Form\BlockForm $form) {
                    $form->text('projectname','项目名称')->required();
                    $form->text('remark','项目说明');
                    $user_id = isset(Admin::user()->pid)?Admin::user()->pid:Admin::user()->id;
                    $res = Company::where('user_id',$user_id)->pluck('name','companyId');
                    $form->select('companyId', '所属公司')->options($res)->required();
                    $form->decimal('lng','经度')->required();
                    $form->decimal('lat','纬度')->required();
                    $form->hidden('user_id');
                    // $form->image('planeJPG','平面底图');
                    $form->hasMany('plans', '平面底图', function (Form\NestedForm $form) {
                        $form->text('name','名称')->required();
                        $form->image('image','平面图')->removable(false)->autoUpload(); 
                    });
                });
            });
            $form->saving(function (Form $form) {
                if ($form->isCreating()) { //新增时存入uid
                    $user_id = isset(Admin::user()->pid)?Admin::user()->pid:Admin::user()->id;
                    $form->user_id = $user_id;
                }
            });
            $form->deleting(function (Form $form) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                Device::where(['projectId'=>$data[0]['projectId']])->update(['projectId'=>0]);
            });
        })->saved(function (Form $form) {
            if ($form->isCreating()) { //新建项目时授权
                $res = Db::table('xfy_project_users')->where(['projectId'=>$form->getKey(),'user_id'=>Admin::user()->id])->first();
                if(!$res){ //给自己授权
                    Db::table('xfy_project_users')->insert(['projectId'=>$form->getKey(),'user_id'=>Admin::user()->id]);
                }
                if(isset(Admin::user()->pid)){ //给上级授权
                    Db::table('xfy_project_users')->insert(['projectId'=>$form->getKey(),'user_id'=>Admin::user()->pid]);
                }
            }
            });
    }
    public function destroy($projectId){
        return $this->form()->destroy($projectId);
    }
    public function edit($id,Content $content){
        return $content
            ->title('项目编辑')
            ->description('编辑')
            // ->body($this->buildPreviewButton())
            // ->body($this->newline())
            ->body($this->form()->edit($id));
    }

    public function show($id){
        return Show::make($id, new Project(), function (Show $show) {
            // $show->layerId;
            $show->field('projectname','项目名称');
            // $show->field('remark','公司备注');
            $show->created_at;
        });
    }
}